package com.kira.scaffoldmvc.ShutDownHook;

import com.kira.scaffoldmvc.ShutDownHook.ThreadPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("")
public class ThreadPoolTaskController {

    @Autowired
    private ThreadPoolExecutor kiraExecutor1;
    
    private final AtomicInteger taskCounter = new AtomicInteger(0);

    @GetMapping("/test")
    public String submitTasks() {
        final int TASK_COUNT = 100;
        long startTime = System.currentTimeMillis();
        
        try {
            // 提交100个任务到线程池
            for (int i = 0; i < TASK_COUNT; i++) {
                final int taskId = taskCounter.incrementAndGet();
                kiraExecutor1.execute(() -> {
                    try {
                        // 模拟任务执行，随机耗时50-200毫秒
                        long sleepTime = (long) (Math.random() * 15000 + 50);
                        Thread.sleep(sleepTime);
                        
                        // 打印任务完成信息
                        System.out.println("任务 " + taskId + " 执行完成，耗时: " + sleepTime + "ms");
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        System.out.println("任务 " + taskId + " 被中断");
                    }
                });
            }
            
            // 返回提交成功信息
            return "成功提交 " + TASK_COUNT + " 个任务到线程池，耗时: " 
                  + (System.currentTimeMillis() - startTime) + "ms";
                  
        } catch (Exception e) {
            return "提交任务失败: " + e.getMessage();
        }
    }
    
    @GetMapping("/status")
    public String getThreadPoolStatus() {
        return "线程池状态: 活跃线程数=" + kiraExecutor1.getActiveCount()
              + ", 队列任务数=" + kiraExecutor1.getQueue().size()
              + ", 已完成任务数=" + kiraExecutor1.getCompletedTaskCount()
              + ", 总任务数=" + kiraExecutor1.getTaskCount();
    }
}
